﻿using System;
using System.Collections.Generic;
using TimedText;
using TimedText.Formatting;
using TimedText.Rendering;
using TimedText.Timing;
using TimedText.Utilities;
using TimedTextLibrary;

namespace Microsoft.Office.PowerPoint.STAMP.TimedText
{
    public static class TimedTextCaptionParser
    {
        static Dictionary<TimeCode, FormattingObject> _formattingObjects = new Dictionary<TimeCode, FormattingObject>();

        public static List<TimeCode> Events
        {
            get;
            set;
        }

        public static IEnumerable<TimedTextCaption> ParseTTML(string sourceText, TimeSpan begin, TimeSpan end)
        {
            Events = new List<TimeCode>();

            TimedTextItem ttml = new TimedTextItem();
            List<TimedTextCaption> list = new List<TimedTextCaption>();

            ttml.SourceText = sourceText;
            ttml.Parse(new TimeCode(begin, SmpteFrameRate.Smpte2997NonDrop),
                         new TimeCode(end, SmpteFrameRate.Smpte2997NonDrop)
                         );
            ttml.Format(new TimeCode(begin, SmpteFrameRate.Smpte2997NonDrop),
                         new TimeCode(end, SmpteFrameRate.Smpte2997NonDrop)
                         );
            
            if (ttml.Parsed)
            {
                IRenderObject pptRenderer = new PPTRenderer();  // dummy renderer.

                foreach (var timeCode in ttml.Events)
                {
                    var caption = ttml.GetTimedTextCaption(pptRenderer, timeCode);
                    //if (!String.IsNullOrEmpty(caption.CaptionText) && caption.EndTime.HasValue && caption.StartTime.HasValue)
                        list.AddRange(caption);
                }
            }
            else
            {
                throw new TimedTextException(ttml.Error);
            }
            return list;
        }
    }
}
